/*
 *   This file is part of YARS.
 *
 *   Foobar is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   YARS is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with YARS.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  Creator: Tom Wadzinski
 * 
 * 
 */

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Globalization;
using System.Web;
using LitJson;
using System.Windows.Forms;
using Microsoft.Win32;

namespace MC_CSPlugin
{
    public class StaticServer
    {
        private MainInterface mainInterface;
        private String pluginDir;
        public void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            try
            {
                HttpListenerContext context = listener.EndGetContext(result);
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                response.ContentType = "text/html";


                FileStream stream = new FileStream(pluginDir + "\\static\\index.html", FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[32768 * 8]; //todo: fix evil hack , do real buffering
                int read = stream.Read(buffer, 0, buffer.Length);

                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
                stream.Close();

                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (Exception e)
            {
                mainInterface.addUserInfoText("Error: " + e.Message + "\n" + e.StackTrace);
            }
            finally
            {
                listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
            }
        }


        public StaticServer(MainInterface main, string[] prefixes)
        {
            mainInterface = main;

            RegistryKey regKey = Registry.LocalMachine;
            regKey = regKey.CreateSubKey("Software\\J. River\\Media Jukebox\\Plugins\\Interface\\YARS Plugin");//must match install script
            pluginDir = (String)regKey.GetValue("Directory");
            mainInterface.addUserInfoText("Plugin dir: " + pluginDir);


            if (!System.Net.HttpListener.IsSupported)
            {
                mainInterface.addUserInfoText(
                    "Windows XP SP2, Server 2003, or higher is required to " +
                    "use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // Create a listener and add the prefixes.
            System.Net.HttpListener listener = new System.Net.HttpListener();
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
                mainInterface.addUserInfoText("Static Server listening at " + s);
            }

            try
            {
                // Start the listener to begin listening for requests.
                listener.Start();
                for (int i = 0; i < 10; i++)
                {

                    IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);

                }


            }
            catch (HttpListenerException ex)
            {
                mainInterface.addUserInfoText("Error: " + ex.Message + "\n" + ex.StackTrace);

            }
            finally
            {
                // Stop listening for requests.
                //listener.Close();
                //mainInterface.addUserInfoText("Done Listening.");
            }
        }
    }
}